package com.astro.dao;

import java.util.Date;
import java.util.List;

import javax.naming.directory.SearchResult;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.astro.common.Constants;
import com.astro.domain.bean.TblUser;

@Repository("userDAO")
public class UserDAO extends BaseHelperDAO {

	public static final String USER_ID 		= "userId";
	public static final String EMAIL 		= "email";

	public TblUser findById(Long userId) throws Exception {
		try {
			String queryString = "from TblUser as model where model.userId = :userId";

			Query query = getCurrentSession().createQuery(queryString);
			query.setParameter("userId", userId);
			query.setMaxResults(1);
			return (TblUser)query.uniqueResult();
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	public TblUser findByEmail(String email) throws Exception {
		try {
			String queryString = "from TblUser as model where model.email = :email";

			Query query = getCurrentSession().createQuery(queryString);
			query.setParameter("email", email);
			query.setMaxResults(1);
			return (TblUser)query.uniqueResult();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List<TblUser> findByProperty(String propertyName, Object value) throws Exception {

		try {

			String queryString = "from TblUser as model where model."
					+ propertyName + "= :propertyName";
			Query query = getCurrentSession().createQuery(queryString);
			query.setParameter("propertyName", value);
			return query.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	/**
	 * Insert customer into database
	 */
	public void addTblUser(TblUser entity) throws Exception {
		// Insert into database
		getCurrentSession().save(entity);
	}
	
	/**
	 * Update user
	 */
	public void updateTblUser(TblUser tblUser) throws Exception {

		Query query = getCurrentSession().getNamedQuery("TblUser.UpdateTblUser");
		query.setParameter("updatedBy", 	tblUser.getUpdatedBy());
		query.setParameter("updatedDate", 	tblUser.getUpdatedDate());
		query.setParameter("userId", 		tblUser.getUserId());
		query.executeUpdate();
	}
	
	/**
	 * Reset user
	 */
	public void resetTblUser(TblUser tblUser) throws Exception {

		if (tblUser != null && tblUser.getUserId() != null) {
			StringBuilder resetQuery = new StringBuilder("update TblUser model set ");
			if (StringUtils.isNotBlank(tblUser.getGroupCode())) {
				resetQuery.append(" model.groupCode	=:groupCode, ");
			}
			if (StringUtils.isNotBlank(tblUser.getLocked())) {
				resetQuery.append(" model.locked	=:locked, ");
			}
			if (StringUtils.isNotBlank(tblUser.getEnabled())) {
				resetQuery.append(" model.enabled	=:enabled, ");
			}
			if (StringUtils.isNotBlank(tblUser.getPassword())) {
				resetQuery.append(" model.password	=:password, ");
			}

			resetQuery.append(" model.updatedBy		=:updatedBy, ");
			resetQuery.append(" model.updatedDate	=:updatedDate ");
			resetQuery.append(" where model.userId	=:userId");
			Query query = getCurrentSession().createQuery(resetQuery.toString());
			query.setParameter("updatedBy", 	tblUser.getUpdatedBy());
			query.setParameter("updatedDate", 	tblUser.getUpdatedDate());
			query.setParameter("userId", 		tblUser.getUserId());

			if (StringUtils.isNotBlank(tblUser.getLocked())) {
				query.setParameter("locked", 	tblUser.getLocked());
			}
			if (StringUtils.isNotBlank(tblUser.getEnabled())) {
				query.setParameter("enabled", 	tblUser.getEnabled());
			}
			if (StringUtils.isNotBlank(tblUser.getPassword())) {
				query.setParameter("password", 	tblUser.getPassword());
			}

			query.executeUpdate();
		}
	}
	
	/**
	 * Delete user
	 */
	public void deleteTblUser(Long userId) throws Exception {

		Query query = getCurrentSession().getNamedQuery("TblUser.DeleteByUserId");
		query.setParameter("userId", userId);
		query.executeUpdate();
	}
	
	/**
	 * Change password
	 */
	public void updatePassword(TblUser tblUser) throws Exception {

		Query query = getCurrentSession().getNamedQuery("TblUser.UpdatePassword");
		query.setParameter("password", 		tblUser.getPassword());
		query.setParameter("updatedBy", 	tblUser.getUpdatedBy());
		query.setParameter("updatedDate", 	tblUser.getUpdatedDate());
		query.setParameter("email", 		tblUser.getEmail());
		query.executeUpdate();
	}

	
	/**
	 * Lock User
	 */
	public void updateLastLogin(String email) throws Exception {

		Query query = getCurrentSession().getNamedQuery("TblUser.UpdateLastLogin");
		query.setParameter("dateLastAccessed", new Date());
		query.setParameter("email", 		email);
		query.executeUpdate();
	}
	
	public boolean checkExistedUser(String email) throws Exception {
		try {
			String queryString = "from TblUser as model where model.email = :email";
			Query query = getCurrentSession().createQuery(queryString);
			query.setParameter("email", email);
			query.setMaxResults(1);
			return (query.uniqueResult() == null)? false: true;
		} catch (RuntimeException re) {
			throw re;
		}
	}

}